package com.mine.spring.service.impl;

import com.mine.spring.dao.AccountDao;
import com.mine.spring.dao.impl.JdbcAccountDaoImpl;
import com.mine.spring.entity.Account;
import com.mine.spring.service.TransferService;

public class TransferServiceImpl implements TransferService {

    // v1 通过实例化
    //private AccountDao accountDao = new JdbcAccountDaoImpl();

    //v2 通过反射调用setAccountDao方法进行注入；
    private AccountDao accountDao;

    @Override
    public void transfer(String fromCardNo, String toCardNo, int money) throws Exception {
        System.out.println("请求进入service方法");
        Account from = accountDao.queryAccountByCardNo(fromCardNo);
        Account to = accountDao.queryAccountByCardNo(toCardNo);

        from.setMoney(from.getMoney() - money);
        to.setMoney(to.getMoney() + money);
        // v1 时这两个update存在无法控制事务的问题
        accountDao.updateAccountByCardNo(to);
        //int i = 4/0; //模拟失败情况
        accountDao.updateAccountByCardNo(from);
    }

    @Override
    public void transfer2(String fromCardNo, String toCardNo, int money) throws Exception {

        Account f1 = new Account();
        f1.setCardNo(fromCardNo);
        Account from = accountDao.queryAccountByCardNo2(f1);

        Account f2 = new Account();
        f2.setCardNo(toCardNo);

        Account to = accountDao.queryAccountByCardNo2(f2);

        from.setMoney(from.getMoney() - money);
        to.setMoney(to.getMoney() + money);
        // v1 时这两个update存在无法控制事务的问题
        accountDao.updateAccountByCardNo(to);
        //int i = 4/0; //模拟失败情况
        accountDao.updateAccountByCardNo(from);
    }

    public void setAccountDao(AccountDao accountDao) {

        //可以在注入的时候通过mybatis 获取

        this.accountDao = accountDao;
    }
}
